// pages/making.js
const myAudio = wx.getBackgroundAudioManager()
import api from '../../utils/api.js'
import util from '../../utils/util.js'
var page = 1
var allPage = 1
var shareData = {}
var savedMid = []
var tid = ''
// 用于保存index传来的mid
var urlMid = ''
//获取应用实例
const app = getApp()
Page({
  data: {
    isIndex:false,
    imgs:[],
    albumData:{},
    temData:[],
    music:{},
    isMusic:false,
    pid:0,
  },

  onLoad: function (options) {
    tid = options.tid
    getApp().setWatcher(this.data, this.watch); // 设置监听器
    page = allPage = 1
    const imgs = app.globalData.makingImgs
    this.setData({imgs})
    this.getTems()
  },

  onShow: function () {
    // 判断播放状态
    if (app.globalData.isMusic == true) {
      this.setData({ isMusic: false })
    }
    this.audioPlay()
    // 获取分享数据
    shareData = util.getShareData()
  },

  // 监听music数据的改变创建音频
  watch: {
    music: function (newValue) {
      app.createMusic(newValue)
    },
    albumData: function (newValue) {
      let id = newValue.id ? newValue.id : newValue.mid
      // 记录播放的id
      const visitTimes = wx.getStorageSync('visitTimes')
      if (visitTimes) {
        if (visitTimes[id]) {
          const times = visitTimes[id]
          visitTimes[id] = parseInt(times) + 1
          wx.setStorageSync('visitTimes', visitTimes)
        } else {
          visitTimes[id] = 1
          wx.setStorageSync('visitTimes', visitTimes)
        }
      } else {
        let data = {}
        data[id] = 1
        wx.setStorageSync('visitTimes', data)
      }
      // 上报微信
      util.visitCount(id, newValue.title)
    }
  },
  // 获取模板数据 
  getTems(){
    let that = this
    const data = {
      m: 'Main',
      length: '10',
      page,
    }
    api.getData(data).then(res=>{
      if(res.data.code == 1){
        const temData = res.data.data
        allPage = temData.allPage
        if(page == 1){
          // 获取index模板数据显示在making页面
          that.setData({
            albumData: app.globalData.shareAlbumData
          })
          that.changeMusic(app.globalData.shareAlbumData)
        }
        that.setData({
          temData: [...this.data.temData, ...temData.list],
        })
      }
    })
  },
  // 更换temid
  changeTemFn(e){
    const id = e.detail
    const newTems = this.data.temData
    const newTem = newTems.filter(function (x) {
      if (x.id == id){
        return x
      }
    })
    this.setData({ albumData: newTem[0]})
    this.changeMusic(newTem[0])
  },
  // 更变背景音乐
  changeMusic(item){
    if (item.audio){
      this.setData({
        isMusic: true,
        music: {
          audio: item.audio,
          title: item.title,
          cover: item.cover
        },
      })
    }else{
      this.audioPause()
    }
  },
  // 暂停背景音乐
  audioPause() {
    myAudio.pause()
    this.setData({
      isMusic: false
    })
  },
  // 播放背景音乐
  audioPlay() {
    myAudio.play()
    this.setData({
      isMusic: true
    })
  },
  // 保存相册
  save() {
    // 当模板与内容完全相同时不保存
    if (savedMid.indexOf(this.data.albumData.id) != -1){
      wx.showToast({
        title: '该相册已经保存了噢！',
        icon: 'none',
        duration: 1000
      })
      return
    }
    let data = {
      m:'Save',
      mid: this.data.albumData.id,
      urls: this.data.imgs,
    }
    const uid = wx.getStorageSync('uid')
    if (uid) { data.uid = uid.uid }
    api.pushSave(data).then(res=>{
      if(res.data.code == 1){
        const datas = res.data.data
        const uidData = { uid: datas.uid }
        wx.setStorageSync('uid', uidData)
        this.setData({
          pid: datas.pid
        })
        this.saveMid()
        wx.showToast({
          title: '恭喜！已保存到第一页的相册里',
          icon: 'none',
          duration: 4000
        })
        // 保存当前相册mid
        savedMid.push(this.data.albumData.id)
      }
    })
  },
  // 下一页
  nextPageFn(){
    if (page<=allPage){
      page++
      this.getTems()
    }
  },
  // 记录保存的mid
  saveMid(){
    // 上报微信
    util.saveCount(this.data.albumData.id, this.data.albumData.title)
    // 上报后端
    const saveTimes = wx.getStorageSync('saveTimes')
    const mid = this.data.albumData.id
    if (saveTimes) {
      if (saveTimes[mid]) {
        const times = saveTimes[mid]
        saveTimes[mid] = parseInt(times) + 1
        wx.setStorageSync('saveTimes', saveTimes)
      } else {
        saveTimes[mid] = 1
        wx.setStorageSync('saveTimes', saveTimes)
      }
    } else {
      let data = {}
      data[mid] = 1
      wx.setStorageSync('saveTimes', data)
    }
  },
  // 分享统计
  countShare() {
    // 上报微信
    util.shareCount(this.data.albumData.id, this.data.albumData.title)
    // 上报后端
    const id = this.data.albumData.id
    let data = {
      m: 'shareTimes',
      id,
    }
    if(tid){ data.tid = tid}
    api.getData(data).then(res => {
      if (res.data.code == 1) {
        console.log('统计分享成功！')
      }
    })
  },
  onShareAppMessage: function () {
    this.countShare()
    let path = `pages/index/index`
    // 防止错误的处理，当没有tid的时候进行，可以忽略。
    if (this.data.pid != 0 && !tid){
      path = `${path}?pid=${this.data.pid}`
    }
    if(tid){
      path = `${path}?tid=${tid}&mid=${this.data.albumData.id}`
    }
    return {
      title: shareData.title,
      imageUrl: shareData.imageUrl,
      path,
    }
  }
})